<?php
/**
 * Created by PhpStorm.
 * User: win7
 * Date: 2018/12/25
 * Time: 22:13
 */
require  'config.php';
$id = $_POST['id'];
$uid = $_POST['uid'];
$btn = $_POST['btn'];
if ($btn == '点赞') {
    $sql1 = "select * from dianzan where uid = $uid and pid = $id";
    $result = mysqli_query($link, $sql1);
    $rows = mysqli_fetch_assoc($result);
    if(!$rows){
        $n_like = $_POST['n_like'] + 1;
        $sql = "insert into dianzan values (null,$uid,$id,1,'')";
        mysqli_query($link, $sql);
        if (mysqli_affected_rows($link) > 0) {
            $sql2 = "update post set n_like = $n_like where id =$id";
            mysqli_query($link, $sql2);
            if (mysqli_affected_rows($link) > 0) {
                $arr = array(
                    'n_like' => $n_like,
                    'name' => '已点赞'
                );
                echo json_encode($arr);
            }
        }
    }else{
        $sql1 = "select * from post where id = $id";
        $result = mysqli_query($link, $sql1);
        $rows = mysqli_fetch_assoc($result);
        $n_like = $rows['n_like'] + 1;
        $sql = "update dianzan set status = 1 where uid =$uid and pid = $id";
        mysqli_query($link, $sql);
        if (mysqli_affected_rows($link) > 0) {
            $sql2 = "update post set n_like = $n_like where id =$id";
            mysqli_query($link, $sql2);
            if (mysqli_affected_rows($link) > 0) {
                $arr = array(
                    'n_like' => $n_like,
                    'name' => '已点赞'
                );
                echo json_encode($arr);
            }
        }
    }
}
    else{
        $sql1 = "select * from post where id = $id";
        $result = mysqli_query($link, $sql1);
        $rows = mysqli_fetch_assoc($result);
        $n_like = $rows['n_like'] - 1;
        $sql = "update dianzan set status = 0 where uid = $uid and pid = $id ";
        mysqli_query($link, $sql);
        if (mysqli_affected_rows($link) > 0) {
            $sql2 = "update post set n_like = $n_like where id =$id";
            mysqli_query($link, $sql2);
            if (mysqli_affected_rows($link) > 0) {
                $arr = array(
                    'n_like' => $n_like,
                    'name' => '点赞'
                );
                echo json_encode($arr);
            }
        }
}